package cn.ymjr.sys.config.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by zhulinghui on 2017/4/18.
 */
public class NullSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object model, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

        jgen.writeStartObject();

        //第一步获取类的属性名称
        Field[] field = model.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
        try {
            for (int j = 0; j < field.length; j++) { // 遍历所有属性
                String name1 = field[j].getName(); // 获取属性的名字
                String name = name1.substring(0, 1).toUpperCase() + name1.substring(1); // 将属性的首字符大写，方便构造get，set方法
                String type = field[j].getGenericType().toString(); // 获取属性的类型

                Method m = model.getClass().getMethod("get" + name);
                Object value = m.invoke(model); // 调用getter方法获取属性值
                if (value == null) {
                    jgen.writeStringField(name1, "");
                }else {
                    jgen.writeStringField(name1, value.toString());
                }

            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        jgen.writeEndObject();





    }



}

